import { Inject, Get, Query, Post, Body } from '@midwayjs/core';
import { CoolController, BaseController, TagTypes, CoolUrlTag } from '@cool-midway/core';
import { DeviceRequestLogService } from '../../../device/service/request-log';
import { DeviceRequestLogEntity } from '../../../device/entity/request-log';

/**
 * 设备请求日志
 */
@CoolUrlTag({
  key: TagTypes.IGNORE_TOKEN,
  value: ['c', 'getLogPhone']
})
@CoolController({
    api: ['add', 'delete', 'update', 'info', 'list', 'page'],
    entity: DeviceRequestLogEntity,
    service: DeviceRequestLogService,
    pageQueryOp: {
        select: ['a.*'],
        join: [],
    },
})
export class AdminABController extends BaseController {
  @Inject()
  deviceRequestLogService: DeviceRequestLogService;

  @Inject()
  ctx;

  @Get('/getLogPhone', { summary: '添加请求日志' })
  async getLogPhone() {
    const {logs, updatedPhoneStudentIdList } = await this.deviceRequestLogService.getLogPhone();
    // 生成 HTML 内容
    const htmlContent = `
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>电话号码日志</title>
    </head>
    <body>
        <table>
          <th>
            <td>电话号码</td>
            <td>学员ID</td>
          </th>
            ${logs.map(obj => `<tr><td>${obj.equipment}</td><td>${obj.phone}</td><td>${obj.name}</td><td>${obj.studentId}</td><td>${obj.sign}</td><td>${obj.createTime}</td></tr>`).join('')}
        </table>
    </body>
    </html>
    `;

    // 设置响应头，指定返回内容为 HTML
    this.ctx.set('Content-Type', 'text/html');
    return this.ctx.body = htmlContent;
  }


  @Get('/c', { summary: '添加请求日志' })
  async addLog(@Query() param: { method: string; params: any }) {
    return this.ok(await this.deviceRequestLogService.addLog('GET', param));
  }

  // 新增 POST 类型的 c 方法
  @Post('/c', { summary: 'POST 方式添加请求日志' })
  async addLogByPost(@Body() param: { method: string; params: any }) {
    // console.log('addLogByPost', param);
    // return this.ok(await this.deviceRequestLogService.addLog('POST', param));
    try {
      await this.deviceRequestLogService.addLog('POST', param);
      return {
        code: 200,
        message: "上传成功",
        data: null
      };
    } catch (error) {
      console.error('addLogByPost 失败', error);
      return {
        code: 400,
        message: "上传失败",
        data: null
      };
    }
  }
}
